package com.hzqy.service.appointment;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.hzqy.commons.service.utils.UserAppointmentJob;
import com.hzqy.commons.utils.CronTriggerUtil;
import com.hzqy.persistence.dao.appointment.UserAppointmentDao;
import com.hzqy.web.vo.wchat.UserAppointmentVo;
@Component("BeanDefineConfigue") 
@Service
public class UserAppointmentServiceBean  implements
ApplicationListener<ContextRefreshedEvent>{
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	private UserAppointmentDao userAppointDao;
	
	public int insertProgramAppointMent(UserAppointmentVo userAppointmentVo){
		return userAppointDao.insertProgramAppointMent(userAppointmentVo);
	}
	
	public int deleteProgramAppointMent(int f_uappointment_id){
		return userAppointDao.deleteProgramAppointMent(f_uappointment_id);
	}
	
	public int updateProgramAppointMent(UserAppointmentVo userAppointmentVo){
		return userAppointDao.updateProgramAppointMent(userAppointmentVo);
	}
	
	public List<UserAppointmentVo> selectProgramAppointMentList(int f_uappointment_userid){
		return userAppointDao.selectProgramAppointMentList(f_uappointment_userid);
	}
	
	public UserAppointmentVo selectProgramAppointMent(int f_uappointment_id){
		return userAppointDao.selectProgramAppointMent(f_uappointment_id);
	}
	
	public int updateAppointMentStatus(UserAppointmentVo userAppointmentVo){
		return userAppointDao.updateAppointMentStatus(userAppointmentVo);
	}

	public void onApplicationEvent(ContextRefreshedEvent event) {
		/**
		 * 判断webapplicationcontent是否加载完毕，未完毕时无法获取bean对象
		 */
		if(event.getApplicationContext().getDisplayName().equals("WebApplicationContext for namespace 'dispatcherServlet-servlet'")){
			/* 用于微信预约功能程序启动加载预约列表，其他程序可以忽略*/
			//initUserAppointment();
		}
	}
	/**
	 * 程序启动是加载定时任务列表
	 * 创建响应任务
	 */
	public void initUserAppointment(){
		List<UserAppointmentVo> userAptVoList=userAppointDao.selectAllUserAppointmentList();
		CronTriggerUtil.shutdownJobs();//停止所有任务
		for(int i=0;i<userAptVoList.size();i++){
			String jobName=String.valueOf(userAptVoList.get(i).getF_uappointment_id());
			String time=userAptVoList.get(i).getF_uappointment_time();
			String message="";
			
			try{
				message=checkDirectiveType(userAptVoList.get(i),userAptVoList.get(i).getF_uappointment_action());
				String timeStr=analysisQuartzDate(time,2,userAptVoList.get(i).getF_uappointment_type());
				if(userAptVoList.get(i).getF_uappointment_type()==1){
					jobName=jobName+"_one";
				}
				switch(userAptVoList.get(i).getF_uappointment_mode()){
					case 2://需要提前时间【修改时间方法为完成】
						String remind_Str=analysisQuartzDate(time,1,userAptVoList.get(i).getF_uappointment_type());
						String message_remind1=checkDirectiveType(userAptVoList.get(i),3);
						CronTriggerUtil.addJob(jobName,"group"+jobName,"trigger"+jobName,"group",UserAppointmentJob.class,remind_Str,message_remind1);
						break;	
					case 3://需要创建到点执行与提前提醒两个任务【修改时间方法为完成】
						String remindStr=analysisQuartzDate(time,1,userAptVoList.get(i).getF_uappointment_type());
						String message_remind=checkDirectiveType(userAptVoList.get(i),3);
						CronTriggerUtil.addJob(jobName+"_remind","group"+jobName,"trigger_r"+jobName,"group",UserAppointmentJob.class,remindStr,message_remind);
						
						CronTriggerUtil.addJob(jobName,"group"+jobName,"trigger"+jobName,"group",UserAppointmentJob.class,timeStr,message);
						break;	
					default:
						CronTriggerUtil.addJob(jobName,"group"+jobName,"trigger"+jobName,"group",UserAppointmentJob.class,timeStr,message);
						break;
				}
			}catch(Exception e){
				LOG.error("创建定时任务失败jobName=="+jobName,e);
			}
		}
		CronTriggerUtil.startJobs();//开始所有任务
	}
	/**
	 * 对需要提醒内容提前时间
	 * @param time
	 * @return
	 * @throws ParseException
	 */
	public String analysisQuartzDate(String time,int type,int action) throws ParseException{
		LOG.debug("time=="+time+"type=="+type+"action=="+action);
		String CRON_DATE_FORMAT_="ss mm HH";
		if(action==1){
			String CRON_DATE_FORMAT="ss mm HH dd MM ? yyyy";
			Date new_=new Date();
			Calendar c = Calendar.getInstance();
			c.setTime(new_);
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH) + 1;
			int day = c.get(Calendar.DAY_OF_MONTH);
			String[] cmds=time.split(" ");
			String dd=cmds[0]+" "+cmds[1]+" "+cmds[2]+" "+day+" "+month+" "+"?"+" "+year;
			SimpleDateFormat sdf = new SimpleDateFormat(CRON_DATE_FORMAT);  
			Date dd_ = sdf.parse(dd); 
			if(type==1){//任务类型为提醒时
				dd_=new Date(dd_.getTime()-300000);
			}
			int m=dd_.compareTo(new_);//验证单次时间是否比当前时间早
			if(m>0){//大于当前时间直接返回
				c.setTime(dd_);
				return (new SimpleDateFormat(CRON_DATE_FORMAT)).format(c.getTime());
			}else{//小于当前时间天数加一
				c.setTime(dd_);
				c.add(Calendar.DATE, 1);
				return (new SimpleDateFormat(CRON_DATE_FORMAT)).format(c.getTime());
			}
		}else{
			if(type==1){//判断是否为提醒
				String[] cmds=time.split(" ");
				String dd=cmds[0]+" "+cmds[1]+" "+cmds[2]+" 1 1 2017";
				SimpleDateFormat sdf = new SimpleDateFormat(CRON_DATE_FORMAT_);  
				Date dd_ = sdf.parse(dd);  
				Date afterDate =new Date(dd_.getTime()-300000);
				String formatTimeStr = sdf.format(afterDate);  
				return formatTimeStr+" "+cmds[3]+" "+cmds[4]+" "+cmds[5];
			}else{
				return time;
			}
		}
	}
	public static void main(String[] args)  {
		try{
			/*String time="00 45 17 ? ? ?";
			String CRON_DATE_FORMAT_="ss mm HH";
			String[] cmds=time.split(" ");
			String dd=cmds[0]+" "+cmds[1]+" "+cmds[2]+" 1 1 2017";
			SimpleDateFormat sdf = new SimpleDateFormat(CRON_DATE_FORMAT_);  
			Date dd_ = sdf.parse(dd);  
			Date afterDate =new Date(dd_.getTime()-300000);
			String formatTimeStr = sdf.format(afterDate);  
			System.out.println(formatTimeStr+" "+cmds[3]+" "+cmds[4]+" "+cmds[5]);*/
			UserAppointmentServiceBean u=new UserAppointmentServiceBean();
			System.out.println(u.analysisQuartzDate("00 45 17 * * ?",1,2));
		}catch(Exception e){
			
		}
	}	
	/**
	 * 根据内容类型创建不同指令
	 * @param action 1节目预约  2动作预约
	 * @param type f_cc_type 
	 * @param userAppointmentVo
	 * @return
	 */
	public String checkDirectiveType(UserAppointmentVo userAppointmentVo,int acction){
		String message="";
		 switch (acction) {//编辑请求指令
			case 2://动作预约
				 if (userAppointmentVo.getF_cc_type()==5){
					message="url|"+userAppointmentVo.getServerid()+"|"+userAppointmentVo.getF_cc_code();
				 }else{
					 message="key|"+userAppointmentVo.getServerid()+"|"+userAppointmentVo.getF_cc_code();
				 }
				break;
			case 3://提醒
				 String str=userAppointmentVo.getF_uappointment_contentname();
				 message="bar|"+userAppointmentVo.getServerid()+"|您预约的《"+str+"》将于5分钟后播放";
				break;	
			default://节目预约
				if (userAppointmentVo.getF_cc_type()==2){
					message="mov|"+userAppointmentVo.getServerid()+"|"+userAppointmentVo.getF_cc_code();
				 }else{
					 message="liv|"+userAppointmentVo.getServerid()+"|"+userAppointmentVo.getF_cc_code();
				 }
				break;
		}
		return message;
	}
}
